package org.changs.nav.ui.nav;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureSupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;

import org.changs.aplug.interf.OnIntervalClickListener;
import org.changs.nav.R;
import org.changs.nav.databinding.BasicsMapFragmentBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.domain.SimpleLocation;
import org.changs.nav.delegate.global.AmapLocationTask;
import org.changs.nav.ui.set.SetMainFragment;

import javax.inject.Inject;

import timber.log.Timber;

/**
 * Created by yincs on 2017/10/16.
 */

public class MapBasicsFragment extends BaseMapFragment {

    private BasicsMapFragmentBinding mBinding;
    private GPSReceiver mGPSReceiver = new GPSReceiver();
    private WifiReceiver mWifiReceiver = new WifiReceiver();
    private AMap mAMap;
    private Marker mCenterMarker;
    @Inject AmapLocationTask mAmapLocationTask;
    @Inject MapSwitchDelegate mMapSwitchDelegate;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.basics_map_fragment, container, false);
        initUI();
        return mBinding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAmapLocationTask.registerListener(mOnLocationListener);
    }

    private void initUI() {
        if (mAMap == null) {
            mAMap = ((TextureSupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
        }
        mAMap.setTrafficEnabled(true);
        mAMap.showBuildings(true);
        mAMap.showMapText(true);
        mAMap.showIndoorMap(true);
//        mAMap.setMapType(AMap.MAP_TYPE_NIGHT);//夜景地图模式
        mAMap.setMapType(AMap.MAP_TYPE_NAVI);//导航地图模式

        UiSettings uiSettings = mAMap.getUiSettings();
        uiSettings.setCompassEnabled(false);
        uiSettings.setScaleControlsEnabled(false);
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setRotateGesturesEnabled(false);
        uiSettings.setZoomControlsEnabled(false);

        mAMap.setMyLocationEnabled(true);
        MyLocationStyle mLocationStyle = mAMap.getMyLocationStyle();
        mLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
//        mLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
        // 自定义精度范围的圆形边框颜色
        mLocationStyle.strokeColor(Color.TRANSPARENT);
        //自定义精度范围的圆形边框宽度
        mLocationStyle.strokeWidth(0);
        // 设置圆形的填充颜色
        mLocationStyle.radiusFillColor(Color.TRANSPARENT);
        mAMap.setMyLocationStyle(mLocationStyle);

        mAMap.setOnMapLoadedListener(() -> {
            mAmapLocationTask.registerListener(mOnLocationListener);
        });

        mAMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            int lastX, lastY;
            int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

            @Override
            public void onTouch(MotionEvent motionEvent) {
                int x = (int) motionEvent.getX();
                int y = (int) motionEvent.getY();
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    lastX = x;
                    lastY = y;
                } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    if (touchSlop < Math.sqrt(x * x + y * y)) {
                        mBinding.vCenter.setVisibility(View.VISIBLE);
                        mBinding.btnGoCar.setVisibility(View.VISIBLE);
                        removeCenterMarker();
                    }
                }
            }
        });

        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (mBinding.vCenter.getVisibility() == View.VISIBLE) {
                    removeCenterMarker();
                    mCenterMarker = mAMap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_click_map_center))
                            .position(cameraPosition.target));
                    mBinding.vCenter.setVisibility(View.GONE);
                }
            }
        });

        mAMap.setOnMarkerClickListener(marker -> {
            if (marker.equals(mCenterMarker)) {

            }
            return false;
        });

        mBinding.vCenter.setVisibility(View.GONE);
        mBinding.btnGoCar.setVisibility(View.GONE);

        mBinding.btnZoomIn.setOnClickListener(v ->
                mAMap.animateCamera(CameraUpdateFactory.zoomOut()));
        mBinding.btnZoomOut.setOnClickListener(v ->
                mAMap.animateCamera(CameraUpdateFactory.zoomIn()));
        mBinding.btnRoads.setOnClickListener(v -> {
            mAMap.setTrafficEnabled(!mAMap.isTrafficEnabled());
            mBinding.btnRoads.setImageResource(mAMap.isTrafficEnabled() ?
                    R.mipmap.auto_ic_roads_close : R.mipmap.auto_ic_roads_open);
        });
        mBinding.btn2d3d.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void intervalOnClick(View v) {
                final MyLocationStyle myLocationStyle = mAMap.getMyLocationStyle();
                if (myLocationStyle.getMyLocationType() != MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER) {
                    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
                    mBinding.btn2d3d.setImageResource(R.mipmap.auto_ic_3d_car);
                } else {
                    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER);
                    mBinding.btn2d3d.setImageResource(R.mipmap.auto_ic_2d_car);
                }
                mAMap.setMyLocationStyle(myLocationStyle);
            }
        });
        mBinding.btnGoCar.setOnClickListener(v -> {
            final Location location = mAMap.getMyLocation();
            mAMap.animateCamera(CameraUpdateFactory
                    .newLatLng(new LatLng(location.getLatitude(), location.getLongitude())), null);
            mBinding.btnGoCar.setVisibility(View.GONE);
            mBinding.vCenter.setVisibility(View.GONE);
            removeCenterMarker();
        });

        mBinding.btnGoDestination.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void intervalOnClick(View v) {
//                getFragmentManager().beginTransaction()
//                        .replace(R.id.rl_container, new SearchMainFragment())
//                        .addToBackStack(MainActivity.TAG_BACK_STACK_DEFAULT)
//                        .commitAllowingStateLoss();
                startFragment(new SearchMainFragment(), MainActivity.TAG_BACK_STACK_DEFAULT);
            }
        });

        mBinding.btnSetting.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void intervalOnClick(View v) {
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.rl_container, new SetMainFragment())
                        .addToBackStack(null)
                        .commitAllowingStateLoss();
            }
        });
    }


    private void removeCenterMarker() {
        if (mCenterMarker != null) {
            mCenterMarker.remove();
            mCenterMarker = null;
        }
    }

    private AmapLocationTask.OnLocationListener mOnLocationListener = new AmapLocationTask.OnLocationListener() {
        @Override
        public void onLocationChanged(int code, String msg, SimpleLocation location) {
            if (code != 0) {
//                    onError(msg);
            } else {
                mAmapLocationTask.unregisterListener(mOnLocationListener);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                mAMap.animateCamera(cameraUpdate);
            }
        }
    };

    private class WifiReceiver extends BroadcastReceiver {

        private boolean isConnected = false;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {//wifi连接上与否
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (NetworkInfo.State.DISCONNECTED.equals(info.getState()) && isConnected) {
                    isConnected = false;
                    Timber.d("onReceive: wifi网络连接断开");
                    mBinding.ivWifi.setImageResource(R.mipmap.auto_ic_status_bar_wifi_no_signal);
                } else if (NetworkInfo.State.CONNECTED.equals(info.getState()) && !isConnected) {
                    isConnected = true;
                    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    //获取当前wifi名称
                    mBinding.ivWifi.setImageResource(R.mipmap.auto_ic_status_bar_wifi_0);
                    Timber.d("onReceive: 连接到网络 " + wifiInfo.getSSID());
                }
            }
        }
    }

    /**
     * 监听GPS 状态变化广播
     */
    private class GPSReceiver extends BroadcastReceiver {

        private boolean isConnected = false;

        public void check() {
            isConnected = isOn(getContext());
            mBinding.ivGps.setImageResource(isConnected ?
                    R.mipmap.auto_ic_status_bar_gps_2 : R.mipmap.auto_ic_status_bar_gps_no_signal);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) {
                boolean isOn = isOn(context);
                if (isOn ^ isConnected) {
                    isConnected = isOn;
                    Timber.d("onReceive: gps 是否开启 = " + isOn);
                    mBinding.ivGps.setImageResource(isConnected ?
                            R.mipmap.auto_ic_status_bar_gps_2 : R.mipmap.auto_ic_status_bar_gps_no_signal);
                }
            }
        }

        private boolean isOn(Context context) {
            LocationManager locationManager = (LocationManager) context.getApplicationContext()
                    .getSystemService(Context.LOCATION_SERVICE);
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
    }
}
